/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 *
 */

import { FileSet } from '@ohos/hvigor';
import * as fse from 'fs-extra';
import path from 'path';
import { CommonConst } from '../const/common-const.js';
import { TaskNames } from './common/task-names.js';
import { TargetTaskService } from './service/target-task-service.js';
import { isSigned } from './sign/sign-util.js';
import { SignProjectRemoteHsp } from './sign-project-remote-hsp.js';
import { SignRemoteHsp } from './sign-remote-hsp.js';
import { DependencyManager } from '../project/dependency/dependency-manager.js';

export class SignModuleRemoteHsp extends SignRemoteHsp {
  constructor(targetService: TargetTaskService) {
    super(targetService, TaskNames.CommonTask.SIGN_MODULE_REMOTE_HSP);
    const moduleOhpmPath = this.moduleModel.getRemoteHspPath();
    const projectOhpmPath = this.service.getProjectModel().getRemoteHspPath();
    const dependencyManager = new DependencyManager(this.projectModel.isFaMode(), this.moduleModel, this.projectModel);
    const { npmDependencies } = dependencyManager.collectAllDependencies();
    this.getModuleSignRemoteHspMap(moduleOhpmPath, npmDependencies);
    this.getProjectSignRemoteHspMap(projectOhpmPath, npmDependencies);
    if (this.allModuleRequiredSignRemoteHspMap.size > 0) {
      this.createProjectRemoteHspCache();
      this.initAllSignRemoteHspList(
        this.allModuleHspPathList,
        this.allModuleRemoteHspPathList,
        this.allModuleSignedRemoteHspList,
        this.allModuleRequiredSignRemoteHspMap,
      );
    }
  }

  taskShouldDo(): boolean {
    return isSigned(this.projectModel);
  }

  /**
   * 判断全局变量promise的值执行不同操作
   * projectUnsigned说明工程级remote_hsp文件不存在或SignProjectRemoteHsp增量未执行，直接执行模块级remote_hsp签名
   * typeof promise为function说明工程级remote_hsp正在签名，所以模块级等待签名结束
   * projectSignSuccesses说明工程级remote_hsp签名成功，直接执行模块级remote_hsp签名
   * @protected
   */
  protected async doTaskAction() {
    await this.moduleSignAction();
  }

  private async moduleSignAction() {
    const projectHspDir = this.projectModel.getCacheRemoteHspPath(this.targetData.getProduct().name);
    const projectRemoteHspCachePath = path.resolve(projectHspDir, CommonConst.REMOTE_HSP_CACHE);
    if (this.allModuleSignedRemoteHspList.length === 0) {
      return;
    }
    this._log.debug(`this.allModuleSignedRemoteHspList ${this.allModuleSignedRemoteHspList}`);
    for (const signOhpmModel of this.allModuleSignedRemoteHspList) {
      await this.submitSignWorker(signOhpmModel, () => {
        this.signRemoteHspCallBack(projectRemoteHspCachePath, signOhpmModel.getOutPutFilePath());
      });
    }
  }

  declareInputFiles(): FileSet {
    return super.declareInputFiles().addEntries([...this.allModuleRemoteHspPathList], {
      isDirectory: false,
    });
  }

  declareOutputFiles(): FileSet {
    return super.declareOutputFiles().addEntries([...this.allModuleHspPathList], { isDirectory: false });
  }

  initTaskDepends(): void {
    const projectOhpmPath = this.service.getProjectModel().getRemoteHspPath();
    if (fse.existsSync(projectOhpmPath)) {
      this.dependsOn(`${this.targetData.getTargetName()}@${SignProjectRemoteHsp.name}`);
    }
  }
}
